const $ = layui.jquery;
const form = layui.form;
$(() => {
    //刷新验证码
    $("#captcha-img").click(function () {
        $(this).attr("src", ctx+"/vm/sys/captcha?t="+Math.random());//让每次的地址都不一样
    });

    //自定义校验规则
    form.verify({
        username: function (val, elem) {
            if (val.length < 6 || val.length > 16) {
                return "用户名必须介于6~16位之间";
            }
        }
    });

    //登录
    $("#login-btn").click(function () {
        let formData = form.val("login-form");
        let pass = form.validate("#login-form");
        if (!pass) {
            return;
        }
        const url = ctx + "/vm/sys/login";
        $.ajax({
            url,
            method: "post",
            dataType: "json",
            data: formData,
            success(resp) {
                if (resp.success) {
                    sessionStorage.setItem("currentAdm",JSON.stringify(resp.data));
                    location.href = ctx + "/vm/sys/index";
                } else {
                    layui.use(function () {
                        let layer = layui.layer;
                        layer.msg(resp.msg || "认证失败，请检查后重试",{icon:0});
                    });
                    $("#captcha-img").click();//刷新验证码
                }
            },
            error(resp) {
                layui.use(function () {
                    let layer = layui.layer;
                    layer.msg(resp.responseJSON.msg || "认证失败，请检查后重试",{icon:2});
                });
                $("#captcha-img").click();//刷新验证码
            }
        });
    });
});